package com.example.kiratest.test;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSONObject;

/**
 * @Author Kira
 * 向钉钉机器人简单发送数据
 */
//基于Webhook简单发送卡片消息
public class KiraCardrEasyMessageSender {
 
    // 钉钉机器人Webhook URL
    private static final String WEBHOOK_URL = "https://oapi.dingtalk.com/robot/send?access_token=9abd4ead51a7b12d84e5906c3be67ed7aff75ad21f9aacedc316e9f0ff75616e";
 
    public static void main(String[] args) throws Exception {
        // 构建卡片消息
        JSONObject cardMessage = new JSONObject();
        cardMessage.put("msgtype", "markdown"); //消息格式
        
        JSONObject markdown = new JSONObject();
        markdown.put("title", "我的卡片消息标题"); //消息标题
        markdown.put("text", "```markdown\n我的基本测试\n```"); //消息文本

        //放入JsonObject里面
        cardMessage.put("markdown", markdown);
 
        // 发送HTTP POST请求
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(WEBHOOK_URL);
            httpPost.setHeader("Content-Type", "application/json");
            
            StringEntity entity = new StringEntity(cardMessage.toJSONString(), "UTF-8");
            httpPost.setEntity(entity);
 
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println("Response: " + responseBody);
            }
        }
    }
}